package com.dayang.websocket;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;



public class HandshakeInterceptor implements org.springframework.web.socket.server.HandshakeInterceptor{
	private  static Logger logger = LogManager.getLogger(HandshakeInterceptor.class);
	
	/* (non-Javadoc)
	 * @see org.springframework.web.socket.server.HandshakeInterceptor#afterHandshake(org.springframework.http.server.ServerHttpRequest, org.springframework.http.server.ServerHttpResponse, org.springframework.web.socket.WebSocketHandler, java.lang.Exception)
	 * 握手访问后
	 */
	@Override
	public void afterHandshake(ServerHttpRequest arg0, ServerHttpResponse arg1,
			WebSocketHandler arg2, Exception arg3) {
		
		logger.info("握手访问后,输出.....");
	}

	/* (non-Javadoc)
	 * @see org.springframework.web.socket.server.HandshakeInterceptor#beforeHandshake(org.springframework.http.server.ServerHttpRequest, org.springframework.http.server.ServerHttpResponse, org.springframework.web.socket.WebSocketHandler, java.util.Map)
	 * 握手访问前
	 * 
	 */
	@Override
	public boolean beforeHandshake(ServerHttpRequest request,
			ServerHttpResponse response, WebSocketHandler handle,
			Map<String, Object> map) throws Exception {
		logger.info("握手访问前,输出.....");	
	    if (request instanceof ServletServerHttpRequest) {  
            HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();  
            String userName = "xq";  
            // 使用userName区分WebSocketHandler，以便定向发送消息  
            // String userName = (String)  
            // session.getAttribute("WEBSOCKET_USERNAME");  
            map.put("WEBSOCKET_USERNAME", userName);  
            servletRequest.getSession().setAttribute("WEBSOCKET_USERNAME", userName); 
		
	    }
		return true;
	}

}
